package com.meritdata.cloud.data.standard.quality.service;

import com.meritdata.cloud.data.base.Page;
import com.meritdata.cloud.data.standard.desensitization.entity.TdDatamaskRule;
import com.meritdata.cloud.data.standard.desensitization.entity.QTdDatamaskRule;
import com.meritdata.cloud.data.standard.quality.dao.IQualityDao;
import com.meritdata.cloud.data.standard.quality.entity.TdDataQualityRule;
import com.meritdata.cloud.data.standard.quality.entity.QTdDataQualityRule;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class QualityService  {
	@Autowired
	private JPAQueryFactory jpaQueryFactory;
	@Autowired
	private IQualityDao dao;

	public void add(TdDataQualityRule datasource) {
		dao.save(datasource);
	}

	public Boolean del(String id) {
		dao.deleteById(Long.valueOf(id));
		return true;
	}
	public Boolean updateState(String ids, Integer state) {
		String[] id = ids.split(",");
		for(int i = 0 ; i < id.length ; i++){
			dao.updatePublishState(Long.valueOf(id[i]),state,new Date());
		}
		return true;
	}
	public Boolean update(String id, String name, String conditionExp, int conditionType, String description) {

		return dao.update(Long.valueOf(id),name,conditionExp,conditionType,description,new Date()) >=0;
	}
	public Page page(Map<String,Object> param) {
		Page p = new Page();
		QTdDataQualityRule qDataQualityRule = QTdDataQualityRule.tdDataQualityRule;
		Integer pageNum = Integer.parseInt((String) param.get("page"));
		Integer sizeNum = Integer.parseInt((String) param.get("rows"));
		p.setPageNum(pageNum);
		p.setPageSize(sizeNum);
		Pageable pageable = PageRequest.of(pageNum-1,sizeNum);
		if(StringUtils.isNotBlank((String)param.get("name"))){
			Predicate predicate = qDataQualityRule.name.like("%"+(String)param.get("name")+"%");
			List<TdDataQualityRule> ls =jpaQueryFactory.selectFrom(qDataQualityRule)
					.where(predicate)
					.offset(pageable.getOffset())
					.limit(pageable.getPageSize())
					.orderBy(qDataQualityRule.updateTime.desc())
					.fetch();
			Long count = jpaQueryFactory.selectFrom(qDataQualityRule)
					.where(predicate)
					.fetchCount();
			p.setTotalCount(count);
			p.setDatas(ls);
			return p;
		}else{
			List<TdDataQualityRule> ls =jpaQueryFactory.selectFrom(qDataQualityRule)
					.offset(pageable.getOffset())
					.limit(pageable.getPageSize())
					.orderBy(qDataQualityRule.updateTime.desc())
					.fetch();
			Long count = jpaQueryFactory.selectFrom(qDataQualityRule)
					.fetchCount();
			p.setTotalCount(count);
			p.setDatas(ls);
			return p;
		}
	}
}
